#include "wooddetectprocessor.h"
#include <QDebug>
#include "Alg/initializationworker.h"
#include "Api_WoodDetect.h"

WoodDetectProcessor::WoodDetectProcessor(QObject *parent)
    : QObject(parent)
{
    initialize();
}

WoodDetectProcessor::~WoodDetectProcessor()
{
    stopWorkerThreads();
}

void WoodDetectProcessor::initialize()
{
    if (m_initialized || m_initializing) return;
    m_initializing = true;

    // 创建初始化工作对象
    InitializationWorker* worker = new InitializationWorker();
    worker->moveToThread(&m_initThread);

    // 连接信号槽
    connect(&m_initThread, &QThread::finished, worker, &QObject::deleteLater);
    connect(worker, &InitializationWorker::initializationFinished, this, [this](bool success) {
        if (success) {
            qDebug() << "start Worker Threads";
            startWorkerThreads();
            m_initialized = true;
        }
        else {
            emit algorithmError("Algorithm initialization failed");
        }
        m_initializing = false;
        m_initThread.quit();
        m_initThread.wait();
    });

    // 启动初始化线程
    m_initThread.start();
    QMetaObject::invokeMethod(worker, "doInitialize", Qt::QueuedConnection);
}

void WoodDetectProcessor::startWorkerThreads()
{
    // 启动图像拼接线程
    QObject::connect(&m_ceilThread, &QThread::started, []{
        Obj<WoodInterFace>::GetInstance()->CeilImagesManager();
    });
    m_ceilThread.start();

    // 启动处理线程
    QObject::connect(&m_processThread, &QThread::started, []{
        Obj<WoodInterFace>::GetInstance()->ProcessParallel();
    });
    m_processThread.start();

    // 结果消费
    QObject::connect(&m_consumerThread, &QThread::started, [] {
        Obj<WoodInterFace>::GetInstance()->Consumer();
        });
    m_consumerThread.start();
}

void WoodDetectProcessor::stopWorkerThreads()
{
    Obj<WoodInterFace>::GetInstance()->SetAllProcess(true);
    Obj<WoodInterFace>::GetInstance()->Release();

    if(m_ceilThread.isRunning()) {
        m_ceilThread.quit();
        m_ceilThread.wait();
    }

    if(m_processThread.isRunning()) {
        m_processThread.quit();
        m_processThread.wait();
    }

    if (m_consumerThread.isRunning()) {
        m_consumerThread.quit();
        m_consumerThread.wait();
    }

    //if(m_initThread.isRunning()) {
    //    m_initThread.quit();
    //    m_initThread.wait();
    //}
}

void WoodDetectProcessor::processWoodImages(std::vector <cv::Mat>& images, int woodflag)
{
    QMutexLocker locker(&m_mutex);
    if(!m_initialized) {
        qWarning() << "Processor not initialized, skipping image processing";
        return;
    }
    // 调用WoodInterFace的SetInputImages方法
    Obj<WoodInterFace>::GetInstance()->SetInputImages(images, woodflag);
}
